package com.mxm.mirai.bot;

import com.mxm.mirai.Application;
import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.service.BotgroupsService;
import com.mxm.mirai.service.impl.BotgroupsServiceImpl;
import com.mxm.mirai.tools.BotTools;
import com.mxm.mirai.tools.MXM_Tools;
import net.dreamlu.mica.http.HttpRequest;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.GroupMessage;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.data.*;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class BotVideo implements Consumer<GroupMessageEvent> {

    @Autowired
    BotgroupsService botgroupsService;
    private static BotVideo botVideo;
    @PostConstruct
    public void init(){
        botVideo=this;
        botVideo.botgroupsService = this.botgroupsService;
    }
//    public static final AtomicBoolean isRunning = new AtomicBoolean(false);
//
//    public static final AtomicReference<Long> runningQQ = new AtomicReference(0L);
//
//    public static final AtomicReference<Long> runningGroup = new AtomicReference(0L);
//
//    public static final AtomicReference<String> imgurl = new AtomicReference("");
//    public static final AtomicReference<String> name = new AtomicReference("");
//    public static final AtomicReference<String> introduce = new AtomicReference("");
//
    private static Map<String,Object> videotitle=null,videourl=null;
    private static VideoData videoData;
    private static Map<String,Object> QQIdGroupId=new HashMap();
    private static BotTools botTools = new BotTools();

    public static final String[] CMD = {"动漫", "电影", "视频"};
    @Override
    public void accept(GroupMessageEvent event) {
        if("0".equals(botVideo.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"BotVideo"))){return;}
        Group group = event.getGroup();//群类
        //String message = event.getMessage().toString();
        String message = event.getMessage().contentToString();//群消息
        long groupId = group.getId();//群号
        long qq = event.getSender().getId();//群发送人号
        videoData = (VideoData) QQIdGroupId.get(qq+""+groupId);
        if(videoData==null){
            videoData = new VideoData();
        }
        videoData.setRunning(true);
        videoData.setRunningQQ(qq);
        videoData.setRunningGroup(groupId);
        stepA(group, groupId, qq, message);
        switch (videoData.getStep()) {//初始值0
            case 1:
                stepB(group, event, qq, message);
                break;
            case 2:
                stepC(group, groupId, qq, message);
                break;
            default:
                break;
        }
    }
    private void stepC(Group group, long groupId, long qq, String message) {
        if (qq != videoData.getRunningQQ() || groupId!=videoData.getRunningGroup()) {return;}
            if (isNumeric(message)) {
                videoData.setStep(0);
                try {
                    Map map= (Map)videoData.getVideourl().get(message);
                    final String imageid = group.uploadImage(new URL(videoData.getImgurl())).getImageId();
                    group.sendMessage(
                            MessageUtils.newImage(imageid).plus(videoData.getName()+"\n"+videoData.getIntroduce()+"\n"+map.get("setnumber")+":"+MXM_config.bottools.DwzUrl("https://acgcat.gitee.io/tools/video.html?"+map.get("videourl")))
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    videoData.setStep(0);
                }
            }
    }
    private void stepB(Group api, GroupMessage bot, long qq, String message) {
        if (qq != videoData.getRunningQQ() || api.getId()!=videoData.getRunningGroup()) {return;}
        if (isNumeric(message)) {
            try {
                videoData.setStep(2);
                BufferedImage imgio =  botTools.TextTurnImage(getVideoB((String) videoData.getVideotitle().get(message)));
                Image img = api.uploadImage(imgio);
                api.sendMessage(img);
//                api.sendMessage(getVideoB((String) videoData.getVideotitle().get(message)));
            }catch (Exception e){
                videoData.setStep(0);
            }
        }
    }
    private void stepA(Group api, long groupId, long qq, String message) {
        boolean isCMD = false;
        for (String s : CMD) {
            if (message.length() > 2 && s.equals(message.substring(0,2))) {
                isCMD = true;
                break;
            }
        }
        if (!isCMD) {
            return;
        }
        try{
            videoData.setStep(1);
            QQIdGroupId.put(qq+""+groupId,videoData);
            BufferedImage imgio =  botTools.TextTurnImage(getVideoA(message.substring(2,message.length())));
            Image img = api.uploadImage(imgio);
            api.sendMessage(img);
//            api.sendMessage(getVideoA(message.substring(2,message.length())));
        }catch (Exception e){
            videoData.setStep(0);
        }
    }

    private static String getVideoA(String name){
        videotitle = new HashMap();
        RequestBody body = null;
        String textname = "";
        try {
            textname = URLEncoder.encode(name,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "编码转换失败！";
        }
//        body = new FormBody.Builder()
//                .add("wd", textname)
//                .add("submit","search")
//                .build();
        String html = "";
        try {
            html = new MXM_Tools().M_URLPost("http://www.zuidazy3.com/index.php?m=vod-search", "wd=" + textname + "&submit=search", null);
        }catch (Exception e){
            videoData.setStep(0);
            return "视频搜索失败!";
        }
        //        try{
//            html = HttpRequest.post("http://www.zuidazy3.com/index.php?m=vod-search")
//                    .body(body)
//                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
//                    .addHeader("Content-Type","application/x-www-form-urlencoded")
//                    .connectTimeout(Duration.ofSeconds(120))
//                    .execute().asString();
//        }catch (Exception e){
//            videoData.setStep(0);
//            return "视频搜索失败!";
//        }
        System.out.println(html);
        Matcher m = Pattern.compile("<li><span class=\"tt\"></span><span class=\"xing_vb4\"><a href=\"(.*?)\" target=\"_blank\">(.*?)<span>(.*?)</span></a></span> <span class=\"xing_vb5\">(.*?)</span> <span class=\"xing_vb6\">(.*?)</span></li>").matcher(html);
        int index = 0;
        String text="";
        while (m.find()) {
            index += 1;
            text += index+"."+m.group(2)+"["+m.group(3)+"]\n["+m.group(4)+"]["+m.group(5)+"]\n";
            videotitle.put(String.valueOf(index),m.group(1));
        }
        videoData.setVideotitle(videotitle);
        if ("".equals(text)){
            videoData.setStep(0);
            return "视频搜索失败！";
        }else {
            return text+"[回复数字可快捷选择]";
        }
    }
    private static String getVideoB(String url){
        String html = HttpRequest.get("http://www.zuidazy3.com"+url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute().asString();
        //System.out.println(html);
        //名称
        videoData.setName(Matcher("<img class=\"lazy\" src=\"(.*?)\" alt=\"(.*?)\" />",html,2,true));
//        name.set(Matcher("<img class=\"lazy\" src=\"(.*?)\" alt=\"(.*?)\" />",html,2,true));
        //图片
        videoData.setImgurl(Matcher("<img class=\"lazy\" src=\"(.*?)\" alt=\"(.*?)\" />",html,1,true));
//        imgurl.set(Matcher("<img class=\"lazy\" src=\"(.*?)\" alt=\"(.*?)\" />",html,1,true));
        //介绍
        videoData.setIntroduce(Matcher("<span class=\"more\" txt=\"([\\s\\S]*?)\">([\\s\\S]*?)</span>",html,1,true));
//        introduce.set(Matcher("<span class=\"more\" txt=\"([\\s\\S]*?)\">([\\s\\S]*?)</span>",html,1,true));
        //集数
        String texttt = Matcher("<h3>([\\s\\S]*?)<span([\\s\\S]*?)>([\\s\\S]*?)</span></h3>([\\s\\S]*?)<ul>([\\s\\S]*?)</ul>",html,5,true);
        Matcher m = Pattern.compile("checked=\"\"/>(.*?)</li>").matcher(texttt);
        int index = 0;
        String text="";
        Map map = null;
        videourl = new HashMap();
        while (m.find()) {
            String[] name_url = m.group(1).split("\\$");
            if(name_url.length!=0){
                map = new HashMap();
                index += 1;
                text+=index+"."+name_url[0]+"\n";
                map.put("setnumber",name_url[0]);
                map.put("videourl",name_url[1]);
                videourl.put(String.valueOf(index),map);
                //System.out.println(name_url[0]+"___"+name_url[1]);
            }
            videoData.setVideourl(videourl);
        }
        return text+"[回复数字可快捷选择]";
    }
    /**
     * 正则获取内容(失败返回null)
     *
     * @param reg   正则
     * @param html  网页
     * @param group 获取正则上第几处内容
     * @param blank 是否清除空格
     * @return
     */
    private static String Matcher(String reg, String html, Integer group, boolean blank) {
        Matcher m = Pattern.compile(reg).matcher(html);
        while (m.find()) {
            String text = m.group(group);
            if (text == null || "".equals(text)) {
                return null;
            }
            if (blank) {
                return text.replace(" ", "").replaceAll(" ", "");
            }
            return text;
        }
        return null;
    }
    /**
     * 判断字符是否为整数
     * @param str
     * @return
     */
    private static boolean isNumeric(String str){
        for (int i = 0; i < str.length(); i++){
            //System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
//        try {
//            System.out.println(URLEncoder.encode("狐妖","UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        String text = getVideoB("/?m=vod-detail-id-88589.html");
//        System.out.println(text);
//        BufferedImage imgio =  botTools.TextTurnImage(text);
//        botTools.Xsimg(botTools.bufferedImageToInputStream(imgio));
    }
}
class VideoData{
    private Boolean isRunning;
    private Long runningQQ;
    private Long runningGroup;
    private String imgurl;
    private String name;
    private String introduce;
    private Integer step = 0;
    private Map<String,Object> videotitle,videourl;

    public Boolean getRunning() {
        return isRunning;
    }

    public void setRunning(Boolean running) {
        isRunning = running;
    }

    public Long getRunningQQ() {
        return runningQQ;
    }

    public void setRunningQQ(Long runningQQ) {
        this.runningQQ = runningQQ;
    }

    public Long getRunningGroup() {
        return runningGroup;
    }

    public void setRunningGroup(Long runningGroup) {
        this.runningGroup = runningGroup;
    }

    public String getImgurl() {
        return imgurl;
    }

    public void setImgurl(String imgurl) {
        this.imgurl = imgurl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIntroduce() {
        return introduce;
    }

    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }

    public Integer getStep() {
        return step;
    }

    public void setStep(Integer step) {
        this.step = step;
    }

    public Map<String, Object> getVideotitle() {
        return videotitle;
    }

    public void setVideotitle(Map<String, Object> videotitle) {
        this.videotitle = videotitle;
    }

    public Map<String, Object> getVideourl() {
        return videourl;
    }

    public void setVideourl(Map<String, Object> videourl) {
        this.videourl = videourl;
    }
}